package com.jcfk.eam.service.equ;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.enums.DeleteFlag;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.equ.EquSparePartsTypeDao;
import com.jcfk.eam.domain.dto.equ.EquSparePartsTypeDTO;
import com.jcfk.eam.domain.po.equ.EquSparePartsType;
import com.jcfk.eam.domain.query.equ.EquSparePartsTypeQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

@Service
public class EquSparePartsTypeService extends BaseService<EquSparePartsTypeDao, EquSparePartsType> {

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<MdmEquipTypeDTO>
     */
    public List<EquSparePartsTypeDTO> getList(EquSparePartsTypeQuery query) {
        // 查询条件
        QueryWrapper<EquSparePartsType> qw = new QueryWrapper<>();
        qw.lambda().eq(query.getAssetKind() != null, EquSparePartsType::getAssetKind, query.getAssetKind());
        qw.lambda().eq(!StrUtil.isEmpty(query.getParentKindId()), EquSparePartsType::getParentKindId, query.getParentKindId());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getKindName()), EquSparePartsType::getKindName, query.getKindName());
        qw.lambda().eq(query.getEnabled() != null, EquSparePartsType::getEnabled, query.getEnabled());
        qw.lambda().eq(EquSparePartsType::getDeleted, DeleteFlag.NOTDELETED.getValue());
        // 查询数据
        List<EquSparePartsType> list = super.list(qw);

        return convertList(list, EquSparePartsTypeDTO.class);
    }


    /**
     * 根据条件获取位置信息树
     *
     * @param query 查询条件
     */
    public List<EquSparePartsTypeDTO> getTree(EquSparePartsTypeQuery query) {
        List<EquSparePartsTypeDTO> tree = new ArrayList<>();
        // 获取所有类型
        List<EquSparePartsTypeDTO> allList = this.getList(query);
        // 排序
        allList.sort(Comparator.comparing(EquSparePartsTypeDTO::getSort));

        Map<String, List<EquSparePartsTypeDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (EquSparePartsTypeDTO node : allList) {
            String parentTypeId = node.getParentKindId();
            parentChildMap.computeIfAbsent(parentTypeId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        return tree;
    }


    /**
     * 根据条件获取位置信息树
     *
     * @param query 查询条件
     */
    public List<EquSparePartsTypeDTO> getAvailableList(EquSparePartsTypeQuery query) {
        List<EquSparePartsTypeDTO> tree = new ArrayList<>();
        // 获取所有类型
        query.setParentKindId("0");
        List<EquSparePartsTypeDTO> allList = this.getList(query);
        // 排序
        allList.sort(Comparator.comparing(EquSparePartsTypeDTO::getSort));

        Map<String, List<EquSparePartsTypeDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (EquSparePartsTypeDTO node : allList) {
            String parentTypeId = node.getParentKindId();
            parentChildMap.computeIfAbsent(parentTypeId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        return tree;
    }

    private static void buildTree(List<EquSparePartsTypeDTO> tree, Map<String, List<EquSparePartsTypeDTO>> parentChildMap, String parentTypeId) {
        List<EquSparePartsTypeDTO> children = parentChildMap.get(parentTypeId);
        if (children != null) {
            for (EquSparePartsTypeDTO child : children) {
                List<EquSparePartsTypeDTO> grandchildren = parentChildMap.get(child.getId());
                if (grandchildren != null) {
                    buildTree(child.getNodes(), parentChildMap, child.getId());
                }
                tree.add(child);
            }
        }
    }


    /**
     * 判断MdmEquipType是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EquSparePartsTypeDTO dto) {
        QueryWrapper<EquSparePartsType> qw = new QueryWrapper<>();
        qw.lambda().eq(EquSparePartsType::getKindName, dto.getKindName());
        Integer count = 0;
        // 修改时添加条件
        if (!StrUtil.isEmpty(dto.getId())) {
            qw.lambda().ne(EquSparePartsType::getId, dto.getId());
        }
        qw.lambda().eq(EquSparePartsType::getAssetKind, dto.getAssetKind());
        qw.lambda().eq(EquSparePartsType::getDeleted, DeleteFlag.NOTDELETED.getValue());

        count = this.baseMapper.selectCount(qw);
        if (count > 0) {
            return RetResult.fail("备件种类名称已存在");
        }

        return RetResult.ok();
    }

    /**
     * 插入资产类型
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EquSparePartsTypeDTO dto) {

        // 保存
        EquSparePartsType item = new EquSparePartsType();
        BeanUtils.copyProperties(dto, item);
        item.setId(IdUtils.simpleUUID());
        this.setDefaultValue(item);
        this.setAllInfo(item);
        super.save(item);
    }

    /**
     * 更新备用类型
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EquSparePartsTypeDTO dto) {

        // 保存
        EquSparePartsType item = new EquSparePartsType();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);
        this.setAllInfo(item);
        super.updateById(item);
    }

    /**
     * 根据批量主键删除备用类型(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EquSparePartsTypeDTO dto) {

        EquSparePartsType item = new EquSparePartsType();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EquSparePartsType> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EquSparePartsType item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreatedUserName(SecurityUtils.getUserName());
            item.setVersion(1L);
            item.setDeleted(DeleteFlag.NOTDELETED.getValue());
            item.setCreateTime(new Date());
        }

        if (item.getSort() == null) {
            item.setSort(1);
        }

        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdatedUserName(SecurityUtils.getUserName());
        item.setLastUpdateTime(new Date());


    }

    /**
     * 根据主键获取备用类型信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EquSparePartsTypeDTO get(String id) {
        // 查询数据
        EquSparePartsType item = this.baseMapper.selectById(id);
        EquSparePartsTypeDTO dto = new EquSparePartsTypeDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    public void setAllInfo(EquSparePartsType item) {
        QueryWrapper<EquSparePartsType> qw = new QueryWrapper<>();
        qw.lambda().eq(EquSparePartsType::getId, item.getParentKindId());

        EquSparePartsType parentType = this.baseMapper.selectOne(qw);
        if (parentType == null) {
            item.setAllId(item.getId());
            item.setAllName(item.getKindName());
        } else {
            item.setAllId(parentType.getAllId() + "," + item.getId());
            item.setAllName(parentType.getAllName() + "," + item.getKindName());
        }
    }

    /**
     * 判断是否有下级
     *
     * @param id
     * @return
     */
    public Boolean isHaveChild(String id) {
        QueryWrapper<EquSparePartsType> qw = new QueryWrapper<>();
        qw.lambda().eq(EquSparePartsType::getParentKindId, id).eq(EquSparePartsType::getDeleted, 0);
        Integer count = this.baseMapper.selectCount(qw);
        return count > 0 ? true : false;
    }





}
